<template>
  <div class="gitee-contribution">
    <div class="contribution-header">
      <h3>Gitee 贡献度</h3>
      <div class="controls">
        <select v-model="selectedYear" @change="updateContributions">
          <option v-for="year in availableYears" :key="year" :value="year">
            {{ year }}年
          </option>
        </select>
        <div class="legend">
          <span>较少</span>
          <div
            v-for="(color, index) in colors"
            :key="index"
            class="legend-item"
            :style="{ backgroundColor: color }"
          />
          <span>较多</span>
        </div>
      </div>
    </div>

    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <div v-else class="contribution-graph">
      <div class="months">
        <span v-for="(month, index) in monthLabels" :key="index" class="month-label">
          {{ month }}
        </span>
      </div>
      <div class="days">
        <span class="day-label">周一</span>
        <span class="day-label">周三</span>
        <span class="day-label">周五</span>
      </div>
      <div class="graph">
        <div
          v-for="(week, weekIndex) in weeks"
          :key="weekIndex"
          class="week"
        >
          <div
            v-for="(day, dayIndex) in week"
            :key="dayIndex"
            class="day"
            :style="{ backgroundColor: day.color }"
            :title="`${day.date}: ${day.count} 次贡献`"
          />
        </div>
      </div>
    </div>

    <div v-if="!loading && !error" class="contribution-stats">
      <div class="stat-item">
        <span class="stat-label">最近一年贡献：</span>
        <span class="stat-value">{{ totalContributions }} 次</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">最长连续贡献：</span>
        <span class="stat-value">{{ maxStreak }} 日</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">最近连续贡献：</span>
        <span class="stat-value">{{ currentStreak }} 日</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import axios from 'axios'
import { ref, computed, onMounted } from 'vue'

// 定义属性
const props = defineProps({
  username: {
    type: String,
    default: 'wjkfree'
  }
})

// 响应式数据
const colors = ['#eeeeee', '#d6e685', '#8cc665', '#44a340', '#1e6823']
const contributionData = ref([])
const loading = ref(false)
const error = ref(null)
const selectedYear = ref(new Date().getFullYear())
const totalContributions = ref(0)
const maxStreak = ref(0)
const currentStreak = ref(0)

// 计算属性
const availableYears = computed(() => {
  const currentYear = new Date().getFullYear()
  const years = []
  for (let i = currentYear - 5; i <= currentYear; i++) {
    years.push(i)
  }
  return years.reverse()
})

// 方法
const getContributionColor = (count) => {
  if (count === 0) return colors[0]
  if (count < 1) return colors[1]
  if (count < 3) return colors[2]
  if (count < 5) return colors[3]
  return colors[4]
}

const weeks = computed(() => {
  const weeksArray = []
  const startDate = new Date(selectedYear.value, 0, 1) // 从选定年份的1月1日开始
  startDate.setDate(startDate.getDate() - startDate.getDay()) // 调整到周日

  // 生成53周的数据
  for (let weekIndex = 0; weekIndex < 53; weekIndex++) {
    const week = []
    // 每周7天
    for (let dayIndex = 0; dayIndex < 7; dayIndex++) {
      const currentDate = new Date(startDate)
      currentDate.setDate(startDate.getDate() + weekIndex * 7 + dayIndex)

      // 确保不超出选定年份
      if (currentDate.getFullYear() > selectedYear.value) break

      // 查找当天的贡献数据
      const dateString = currentDate.toISOString().split('T')[0]
      const contribution = contributionData.value.find(item => item.date === dateString)

      if (contribution) {
        week.push({
          date: contribution.date,
          count: contribution.count,
          color: getContributionColor(contribution.count)
        })
      } else {
        week.push({
          date: dateString,
          count: 0,
          color: colors[0] // 没有贡献的日期使用默认颜色
        })
      }
    }
    if (week.length > 0) {
      weeksArray.push(week)
    }
  }

  return weeksArray
})

const monthLabels = computed(() => {
  const months = []
  const startMonth = 0 // 从1月开始

  for (let i = 0; i < 12; i++) {
    const monthIndex = (startMonth + i) % 12
    const date = new Date(selectedYear.value, monthIndex, 1)

    if (i === 0 || i % 2 === 0) {
      months.push(date.toLocaleDateString('zh-CN', { month: 'short' }))
    } else {
      months.push('')
    }
  }
  return months
})

const isSameDay = (date1, date2) => {
  return date1.getFullYear() === date2.getFullYear() &&
         date1.getMonth() === date2.getMonth() &&
         date1.getDate() === date2.getDate()
}

const calculateStats = (data) => {
  console.log('🚀 ~ calculateStats ~ data:', data)

  // 1. 总贡献次数
  totalContributions.value = data.reduce((sum, item) => sum + item.count, 0)

  // 2. 排序数据（按日期升序）
  const sortedData = [...data].sort((a, b) => new Date(a.date) - new Date(b.date))

  // 3. 计算最长连续贡献（maxStreak）
  let currentStreakCount = 0
  let maxStreakCount = 0
  let previousDate = null

  for (const item of sortedData) {
    const currentDate = new Date(item.date)

    if (item.count > 0) {
      if (!previousDate || !isSameDay(currentDate, previousDate)) {
        currentStreakCount = 1
      } else {
        currentStreakCount++
      }

      maxStreakCount = Math.max(maxStreakCount, currentStreakCount)
      previousDate = currentDate
    }
  }

  maxStreak.value = maxStreakCount

  // 4. 计算最近连续贡献（currentStreak）
  let recentStreakCount = 0
  const today = new Date()
  const checkDate = new Date(today)

  for (let i = 0; i < 365; i++) {
    const dateString = checkDate.toISOString().split('T')[0]
    const contribution = data.find(item => item.date === dateString)

    if (contribution && contribution.count > 0) {
      recentStreakCount++
      checkDate.setDate(checkDate.getDate() - 1)
    } else {
      break
    }
  }

  currentStreak.value = recentStreakCount
}

// 生成模拟的贡献数据（备用方案）
const generateContributionData = () => {
  const data = []
  const now = new Date()

  // 生成过去一年的数据
  for (let i = 365; i >= 0; i--) {
    const date = new Date(now)
    date.setDate(date.getDate() - i)
    const dateString = date.toISOString().split('T')[0]

    // 随机生成贡献次数（模拟真实数据）
    const count = Math.floor(Math.random() * 10)
    if (count > 0) {
      data.push({ date: dateString, count })
    }
  }

  return data
}

// 获取贡献数据
const fetchContributions = async() => {
  loading.value = true
  error.value = null

  try {
    // 获取用户贡献数据
    const response = await axios.get(`gitee/${props.username}/contribution_timeline?url=%2F${props.username}%2Fcontribution_timeline&scope=my&day=&start_date=&end_date=&year=&limit=1000&prev_id=&_=1757120193643`)
    console.log('🚀 ~ fetchContributions ~ response:', response)
    const rawData = response.data

    // 处理数据，按日期统计贡献次数
    const contributionMap = {}

    rawData.forEach(item => {
      // 从 created_at 提取日期部分
      const date = item.created_at.split('T')[0]

      if (contributionMap[date]) {
        contributionMap[date]++
      } else {
        contributionMap[date] = 1
      }
    })

    // 转换为数组格式
    const processedData = Object.keys(contributionMap).map(date => ({
      date,
      count: contributionMap[date]
    }))

    contributionData.value = processedData
    calculateStats(processedData)
  } catch (err) {
    error.value = `获取贡献数据失败: ${err.message}`
    // 出错时使用模拟数据
    contributionData.value = generateContributionData()
    calculateStats(contributionData.value)
  } finally {
    loading.value = false
  }
}

// 更新贡献数据（当年份改变时调用）
const updateContributions = () => {
  // 这里可以添加根据年份过滤数据的逻辑
  // 当前实现显示所有数据，但月份标签会根据选定年份变化
}

// 组件挂载时获取数据
onMounted(() => {
  fetchContributions()
})
</script>

<style scoped>
.gitee-contribution {
  width: 100%;
  height: 260px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
  color: #fff;
  border-radius: 6px;
  box-sizing: border-box;
}

.contribution-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.contribution-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.controls {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.controls select {
  padding: 5px 10px;
  font-size: 12px;
  border-radius: 4px;
}

.legend {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
}

.legend-item {
  width: 15px;
  height: 15px;
  border-radius: 2px;
}

.contribution-graph {
  position: relative;
  overflow-x: auto;
  padding-bottom: 20px;
}

.months {
  display: flex;
  margin-bottom: 5px;
  margin-left: 25px;
  height: 15px;
}

.month-label {
  min-width: 20px;
  font-size: 10px;
  text-align: center;
  flex: 1;
}

.days {
  position: absolute;
  top: 35px;
  left: 0;
  display: flex;
  justify-content: space-around;
  width: 20px;
  height: 110px;
  flex-direction: column;
}

.day-label {
  height: 15px;
  font-size: 10px;
  line-height: 15px;
}

.graph {
  display: flex;
  gap: 3px;
  margin-left: 25px;
}

.week {
  display: flex;
  flex-direction: column;
  gap: 3px;
}

.day {
  width: 15px;
  height: 15px;
  border: 1px solid rgb(27 31 35 / 6%);
  border-radius: 2px;
}

.loading,
.error {
  padding: 40px 20px;
  text-align: center;
  color: #586069;
}

.error {
  color: #d73a49;
}

.contribution-stats {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.stat-item {
  text-align: center;
}

.stat-label {
  font-size: 12px;
}

.stat-value {
  font-size: 14px;
  font-weight: 600;
}
</style>
